package com.woniuxy.oldmanapi.service;

import com.woniuxy.oldmanapi.entity.Caretype;
import com.woniuxy.oldmanapi.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CareTypeService {
    @Autowired
    CaretypeMapper caretypeMapper;
    @Autowired
    CareprojectMapper careprojectMapper;
    @Autowired
    CareCareprojectMapper careCareprojectMapper;
    @Autowired
    CareMapper careMapper;
    @Autowired
    OlderMapper olderMapper;


    public List<Caretype> findAll() {
     return   caretypeMapper.selectAll();
    }

    public void addType(Caretype caretype) {
        caretypeMapper.insert(caretype);
    }

    public void modifyType(Caretype caretype) {
        caretypeMapper.updateByPrimaryKey(caretype);
    }

    //删除
    @Transactional
    public void removeType(int typeid) {
        //删除==查询出此类所有的护理级别--被护理级别使用否-->查询这些护理级别是否被使用
        List<Integer> careIds = careCareprojectMapper.selectByTypeId(typeid);
        if(careIds.size()<1){
            //没有护理级别用此类项目，删除项目和类型
            caretypeMapper.deleteByPrimaryKey(typeid);
            careprojectMapper.removeByTypeId(typeid);
            return;
        }
        List<Integer> olderIds=olderMapper.selectByCareIds(careIds);
        if(olderIds.size()>0){
            //此类服务中有的护理级别被使用==不能删除
            throw  new RuntimeException("此护理项目类别有长者正接受服务，不可删除！");
        }else {
            // 没有被使用-->
            // 1.删除类别；2.删除careproject表此类别项目；4.删除护理级别套餐；5.删除护理级别的明细表（中间表）
            caretypeMapper.deleteByPrimaryKey(typeid);
            careprojectMapper.removeByTypeId(typeid);
            careMapper.removeBeachByIds(careIds);
            careCareprojectMapper.removeBeachByCareids(careIds);

        }


    }
}
